package store.lunangangster.bpmn.converter.parser;

import javax.xml.stream.XMLStreamReader;
import org.apache.commons.lang3.StringUtils;
import store.lunangangster.bpmn.model.BaseElement;
import store.lunangangster.bpmn.model.BpmnModel;
import store.lunangangster.bpmn.model.UserTask;
import store.lunangangster.bpmn.model.UserTask.Candidate;
import store.lunangangster.bpmn.util.XmlStreamUtil;

public class PotentialOwnerParser extends BaseChildElementParser {

  @Override
  public void parseChild(XMLStreamReader xsr, BaseElement parentElement, BpmnModel model) throws Exception {
    // no check
    UserTask userTask = (UserTask) parentElement;
    String resourceName = XmlStreamUtil.toNext(xsr);
    if (resourceName == null) {
      return;
    }
    if (ELEMENT_RESOURCE_ASSIGNMENT.equals(resourceName)) {
      String express = XmlStreamUtil.toNext(xsr);
      if (ELEMENT_FORMAL_EXPRESS.equals(express)) { // 可执行表达式的解析
        String content = xsr.getElementText();
        userTask.setCandidate(this.parseCandidate(content));
      }
    }

  }

  private Candidate parseCandidate(String content) {
    if (StringUtils.isBlank(content)) {
      return new Candidate();
    }

    boolean userFound = false;
    boolean groupFound = false;
    final String userPrefix = "user(";
    final String groupPrefix = "group(";
    final String suffix = ")";

    String username = null;
    String group = null;

    content = content.trim();
    String[] split = content.split("\\s*,\\s*");
    for (String s : split) {
      if (userFound && groupFound) {
        break;
      }

      if (s.endsWith(suffix)) {

        if (!userFound && s.startsWith(userPrefix)) {
          userFound = true;
          username = s.substring(userPrefix.length(), s.length() - 1);
        } else if (!groupFound && s.startsWith(groupPrefix)) {
          groupFound = true;
          group = s.substring(groupPrefix.length(), s.length() - 1);
        }
      }
    }
    if (userFound || groupFound) {
      return new Candidate(username, group);
    } else if (split.length == 1) {
      return new Candidate(null, split[0]);
    }
    return null;
  }

  @Override
  public String getTargetName() {
    return ELEMENT_POTENTIAL_OWNER;
  }
}
